package com.sen.gateway.filter;

import cn.hutool.core.util.IdUtil;
import com.sen.common.common.constrant.CommonConstrant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


/**
 * @author esjiang
 */
@Component
@Order(Integer.MIN_VALUE)
@Slf4j
public class GlobalTraceFilter implements WebFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String traceId = IdUtil.fastSimpleUUID();
        MDC.put(CommonConstrant.TRACE_NAME, traceId);
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(h -> h.add(CommonConstrant.X_TRACE_HEADER, traceId))
                .build();
        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        log.info("gateway 注入MDC：{},url:{}",traceId,exchange.getRequest().getURI());
        return chain.filter(build);
    }
}
